import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import type { Slice, AsyncThunk, ActionReducerMapBuilder, PayloadAction } from '@reduxjs/toolkit'
import { getRanking, type GetRankingParams } from './rankingAPI'
import { DataType } from '@/pages/Ranking/Table'
import { v4 } from 'uuid'

interface InitialState {
  params: GetRankingParams,
  table: {
    status: 'init' | 'loading' | 'success' | 'error',
    data?: Res,
    params?: GetRankingParams
  }
  create: {
    type: 'create' | 'update',
    open: boolean,
    record?: DataType
  }
}

const initialState: InitialState = {
  params: {
    rank_type: undefined
  },
  table: {
    status: 'init'
  },
  create: {
    type: 'create',
    open: false
  }
}

type Res = {
  data: {
    rank_reward_config: DataType[]
  }
}
type AsyncRes = {
  res: Res,
  params: GetRankingParams
}
export const getRankingAsync: AsyncThunk<AsyncRes, GetRankingParams, {}> = createAsyncThunk<AsyncRes, GetRankingParams, {}>('ranking/getRankingAsync', async params => {
  const res: Res = await getRanking(params)
  return {
    res, params
  }
})
const tableStatus = (builder: ActionReducerMapBuilder<InitialState>) => {
  builder.addCase(getRankingAsync.pending, state => {
    state.table.status = 'loading'
  }).addCase(getRankingAsync.fulfilled, (state, action) => {
    state.table.status = 'success'
    if(Array.isArray(action.payload.res?.data?.rank_reward_config)){
      action.payload.res.data.rank_reward_config.forEach(i => i.uuid = v4())
    }
    state.table.data = action.payload.res
    state.table.params = action.payload.params
  }).addCase(getRankingAsync.rejected, state => {
    state.table.status = 'error'
  })
}

type Reducers = {
  changeParams: (state:InitialState, action:PayloadAction<Partial<InitialState['params']>>) => void,
  changeCreate: (state: InitialState, action: PayloadAction<Partial<InitialState['create']>>) => void
}
type Selectors = {}
const rankingSlice: Slice<InitialState, Reducers, 'ranking', 'ranking', Selectors> = createSlice<InitialState, Reducers, 'ranking', Selectors, 'ranking'>({
  name: 'ranking',
  initialState,
  reducers: {
    changeParams(state, action){
      state.params = {
        ...state.params,
        ...action.payload
      }
    },
    changeCreate(state, action){
      state.create = {
        ...state.create,
        ...action.payload
      }
    }
  },
  extraReducers(builder) {
    tableStatus(builder)
  }
})

export const { changeParams, changeCreate } = rankingSlice.actions

export default rankingSlice.reducer
